package com.catazy.jetpackstudy.act2.chapter4.socket;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.catazy.jetpackstudy.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @作者: Tao
 * @日期: 2025/2/8
 * @时间: 13:41
 * @描述:
 */
public class TcpClientActivity extends AppCompatActivity {

    private Socket mClientSocket;
    private PrintWriter mPrintWriter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.serial).setOnClickListener(v -> {
            Log.e("TAG", "onClick: ");
            new Thread() {
                @Override
                public void run() {
                    mPrintWriter.println("客户端发送一条消息");
                }
            }.start();
        });

        Intent intent = new Intent(this, TCPServerService.class);
        startService(intent);

        new Thread() {

            @Override
            public void run() {
                connectServer();
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        if (mClientSocket != null) {
            try {
                mClientSocket.shutdownInput();
                mClientSocket.close();
            } catch (Exception e) {
                Log.e("TAG", "connectServer: ", e);
            }
        }
        super.onDestroy();
    }

    private void connectServer() {
        Socket socket = null;
        while (socket == null) {
            try {
                // 创建一个Socket连接
                socket = new Socket("localhost", 8688);
                mClientSocket = socket;
                mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            } catch (Exception e) {
                // 连接失败就等待2秒再尝试重连
                SystemClock.sleep(2000);
            }
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (!TcpClientActivity.this.isFinishing()) {
                // 从服务器读取数据
                String msg = br.readLine();
                if (msg != null) {
                    Log.e("TAG", "msg from server:" + msg);
                }
            }
            try {
                br.close();
                socket.close();
                mPrintWriter.close();
            } catch (Exception e) {
                Log.e("TAG", "connectServer: ", e);
            }
        } catch (Exception e) {
            Log.e("TAG", "connectServer: ", e);
        }
    }
}
